package com.hay.pay.util;

import com.alibaba.fastjson.JSONObject;
import com.hay.pay.exception.PayException;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author LiMouRen
 * @date 2024/1/26
 */
@Slf4j
public class WebUtil {

    /**
     * 获取请求路径参数
     */
    public static Map<String,String> getRequestPathParam(HttpServletRequest request) {
        HashMap<String, String> paramMap = new HashMap<>(16);
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (String key : parameterMap.keySet()) {
            String[] parameter = parameterMap.get(key);
            paramMap.put(key,parameter[0]);
        }
        return paramMap;
    }

    /**
     * 获取请求路径参数
     */
    public static <T> T getRequestPathParam(HttpServletRequest request,Class<T> toClass) {
        return JSONObject.parseObject(JSONObject.toJSONString(getRequestPathParam(request)),toClass);
    }

    /**
     * 获取请求体参数
     * 注意在spring 中 请求体流只能读取一次(引入本jar包则可重复使用该方法)
     * <a href="https://blog.csdn.net/m0_49044558/article/details/119759388">解决方法</a>
     * @see com.hay.pay.filter.HttpServletRequestReplacedFilter
     */
    public static String getRequestBody(HttpServletRequest request) {
        BufferedReader br = null;
        try {
            StringBuilder result = new StringBuilder();
            br = request.getReader();
            for (String line; (line = br.readLine()) != null; ) {
                result.append(line);
            }
            return result.toString();
        } catch (IOException e) {
            log.info("getRequestBody error:{}",e.getMessage(),e);
            throw new PayException(e.getMessage());
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static Map<String,String> getHeaderParams(HttpServletRequest request){
        Map<String, String> params = new HashMap<>(16);
        Enumeration<String> headers = request.getHeaderNames();
        while(headers.hasMoreElements()) {
            String headerName = (String)headers.nextElement();
            String headerValue = request.getHeader(headerName);
            params.put(headerName,headerValue);
        }
        return params;
    }

}
